import { AxiosCall, Call } from './Call';
import { Interceptor } from './Interceptor';
import { Request } from './Request';
import { Response } from './Response';

export class RealInterceptorChain implements Interceptor.Chain {
  private calls = 0

  constructor(
    public call: AxiosCall,
    private interceptors: Array<Interceptor>,
    private index: number,
    public request: Request
  ) {
  }

  getRequest(): Request {
    return this.request;
  }

  proceed(request: Request): Promise<Response> {
    if (this.index >= this.interceptors.length) {
      throw Error()
    }

    this.calls++
    const next = this.copy(this.index + 1, request)
    const interceptor = this.interceptors[this.index]
    const response = interceptor.intercept(next)
    if (!response) {
      throw Error(`interceptor ${interceptor} returned null`)
    }
    return response
  }

  getCall(): Call {
    return this.call;
  }

  private copy(
    index: number,
    request: Request
  ): RealInterceptorChain {
    return new RealInterceptorChain(this.call, this.interceptors, index, request)
  }
}